package com.mewpipe.dao.jpa;

import java.util.List;

import javax.persistence.EntityManager;
import javax.persistence.EntityManagerFactory;
import javax.persistence.Query;

import com.mewpipe.dao.CommentDao;
import com.mewpipe.entity.Comment;
import com.mewpipe.entity.Video;

public class JpaCommentDao implements CommentDao{
	
	private EntityManagerFactory emf;


	public JpaCommentDao(EntityManagerFactory emf) {
		this.emf = emf;
	}


	@Override
	public Long addComment(Comment _comment) {
		
		EntityManager em = emf.createEntityManager();
		try {
			em.getTransaction().begin();
			em.persist(_comment);
			em.getTransaction().commit();
		
			em.refresh(_comment);
			return _comment.getId();
		} 
		
		
		finally {
			if(em.getTransaction().isActive()) em.getTransaction().rollback();
			em.close();
		
		}
			}


	@Override
	public List<Comment> getAllCommentByVideoId(long id) {
List<Comment> return_list= null ;
		
		EntityManager em = emf.createEntityManager();
	
		
		Query query= em.createQuery("SELECT CommentTable FROM Comment CommentTable ,LnkCommentVideo LinkTable WHERE CommentTable.id = LinkTable.idComment AND LinkTable.idVideo="+ id);
		//Query query = em.createSQLQuery("SELECT ID, NAME, BIRTHDATE FROM CATS").addEntity(Video.class);
		try {			
			return_list = (List<Comment>) query.getResultList();
			} 
		
		finally {
			em.close();
				}
		return return_list;
			}


	@Override
	public Comment GetCommentById(long id) {
		Comment return_comment;
		EntityManager em = emf.createEntityManager();
		try {
			em.getTransaction().begin();
			return_comment = em.find(Comment.class,id);
			em.getTransaction().commit();
			
		} 
		
		
		finally {
			if(em.getTransaction().isActive()) em.getTransaction().rollback();
			em.close();
		
		}
		
			return return_comment;
	}

	@Override
	public void updateComment(Comment _comment) {
		
			
			EntityManager em = emf.createEntityManager();
			
			
			try {
				
	            em.getTransaction().begin();
	            em.merge(_comment);
	            em.getTransaction().commit();
				
			} finally {
				
				em.close();
			}
		
		
		
	}
}


